package com.ruoyi.business.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.business.service.SmsService;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Tellsea
 * @date 2024−06−25
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    private static final Long SMS_CLOSE_ID = 6L;

    @Autowired
    private ISysConfigService configService;

    @Override
    public void setSmsClose(String smsClose) {
        SysConfig sysConfig = configService.selectConfigById(SMS_CLOSE_ID);
        sysConfig.setConfigValue(smsClose);
        configService.updateConfig(sysConfig);
    }

    @Override
    public String getSmsClose() {
        SysConfig sysConfig = configService.selectConfigById(SMS_CLOSE_ID);
        return sysConfig.getConfigValue();
    }

    @Override
    public void sendMessage(String phone, String content) {
        SysConfig sysConfig = configService.selectConfigById(SMS_CLOSE_ID);
        if (Boolean.parseBoolean(sysConfig.getConfigValue())) {
            // 关闭短信
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("phones", new String[]{phone});
        params.put("content", content);
        try {
            log.info("发送短信信息，{}", JSON.toJSONString(params));
            String response = HttpUtil.post("https://ydyxkfyy.huashan.org.cn:5932/cdr/sendMsg", JSONUtil.toJsonStr(params));
            log.info("短信发送响应结果，{}",response);
            JSONObject result = JSONObject.parseObject(response);
            if(result==null || !result.getBoolean("success")){
                throw new BaseException("短信发送失败");
            }
            JSONObject innerResult = result.getJSONObject("result");
            String callESBResult = innerResult.getString("CallESBResult");
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(callESBResult)));
            NodeList isSucceedList = document.getDocumentElement().getElementsByTagName("IsSucceed");
            if(isSucceedList.getLength() == 0){
                return;
            }
            Node isSucceed = document.getDocumentElement().getElementsByTagName("IsSucceed").item(0);
            Node message = document.getDocumentElement().getElementsByTagName("Message").item(0);
            if(!Boolean.parseBoolean(isSucceed.getTextContent())){
                throw new BaseException(message.getTextContent());
            }
        } catch (Exception e) {
            log.error("短信发送失败：{}", e.getMessage(),e);
            throw new BaseException("短信发送失败");
        }
    }

    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        String dd="{\"success\":true,\"result\":{\"CallESBResult\":\"<Result><IsSucceed>true</IsSucceed><MessageCode>100</MessageCode><Message>Error occurred processing message on filter '服务调用地址参数查询': Caught exception while parsing the message,Nested exception was 'com.orchestral.rhapsody.module.api_2_0.module.filter.FilterProcessingException': Caught exception while parsing the message,Nested exception was 'com.orchestral.rhapsody.module.api_2_0.impl.adapter.out.MessageFormatExceptionAdapter': Failed to get xml message XPath context of message.,Nested exception was 'com.orchestral.rhapsody.message.parsing.format.MessageFormatException': Failed to get xml message XPath context of message.,Nested exception was 'com.orchestral.rhapsody.message.parsing.xpath.XPathException': Failed to get message context.,Nested exception was 'org.xml.sax.SAXParseException': The reference to entity \\\"registerIds\\\" must end with the ';' delimiter.</Message></Result>\"}}";
        JSONObject result = JSONObject.parseObject(dd);
        if(result==null || !result.getBoolean("success")){
            throw new BaseException("短信发送失败");
        }
        JSONObject innerResult = result.getJSONObject("result");
        String callESBResult = innerResult.getString("CallESBResult");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(callESBResult)));
        Node isSucceed = document.getDocumentElement().getElementsByTagName("IsSucceed").item(0);
        Node message = document.getDocumentElement().getElementsByTagName("Message").item(0);
        if(Boolean.parseBoolean(isSucceed.getTextContent())){
            System.out.println("请求成功");
        }else{
            System.out.println(message.getTextContent());
        }
    }
}
